package com.homeWorkMapReduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.util.HashMap;

public class StudentsMapReduce extends Configured implements Tool {
    private static String[] tokens;

    public static void main(String[] args) throws Exception {
        System.exit(ToolRunner.run(new StudentsMapReduce(), args));
    }

    @Override
    public int run(String[] strings) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "score calculator");
        job.setJarByClass(this.getClass());
        job.setMapperClass(StudentMapper.class);
        job.setReducerClass(StudentReduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setJobName(tokens[1].toString());
        FileInputFormat.addInputPath(job, new Path("input/chinese.txt"));
        FileInputFormat.addInputPath(job, new Path("input/math.txt"));
        FileInputFormat.addInputPath(job, new Path("input/english.txt"));
        FileOutputFormat.setOutputPath(job, new Path("output"));

        return job.waitForCompletion(true) ? 0 : -1;
    }

    static class StudentMapper extends Mapper<LongWritable, Text, Text, Text> {

        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            String line = value.toString();
            tokens = line.split("\\|");
            String name = tokens[1];
            String subject = tokens[0];
            String score = tokens[2];
            context.write(new Text(name), new Text(subject + ": " + score));
        }
    }

    static class StudentReduce extends Reducer<Text, Text, Text, Text> {
        @Override
        protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            HashMap<String, Integer> scores = new HashMap<>();

            for (Text value : values) {
                String[] tokens = value.toString().split(": ");
                String subject = tokens[0];
                int score = Integer.parseInt(tokens[1]);

                scores.put(subject, scores.getOrDefault(subject, 0) + score);
            }

            int totalScore = scores.values().stream().mapToInt(Integer::intValue).sum();
            int averageScore = totalScore / scores.size();

            StringBuilder output = new StringBuilder();
            output.append(key.toString()).append(" ");
            for (String subject : scores.keySet()) {
                output.append(subject).append(":").append(scores.get(subject)).append(",");
            }
            output.append("总分:").append(totalScore).append(",平均分:").append(averageScore);

            context.write(key, new Text(output.toString()));
        }
    }
}
